package com.nanako.service.impl;

import com.baomidou.mybatisplus.core.conditions.Wrapper;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.nanako.common.BaseContext;
import com.nanako.dao.ShoppingCartMapper;
import com.nanako.entity.Setmeal;
import com.nanako.entity.ShoppingCart;
import com.nanako.service.SetmealService;
import com.nanako.service.ShoppingCartService;
import org.apache.commons.lang3.ObjectUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

@Service
public class ShoppingCartServiceImpl extends ServiceImpl<ShoppingCartMapper, ShoppingCart> implements ShoppingCartService {
    @Autowired
    private SetmealService setmealService;

    @Override
    public ShoppingCart addShoppingCart(ShoppingCart shoppingCart) {
        LambdaQueryWrapper<ShoppingCart> wrapper = new LambdaQueryWrapper<>();
        // 必须添加当前用户的id
        wrapper.eq(ShoppingCart::getUserId, BaseContext.getCurrentId());
        // 判断本次添加进购物车的是菜品还是套餐
        Long dishId = shoppingCart.getDishId();
        if (ObjectUtils.isNotEmpty(dishId)) {
            wrapper.eq(ShoppingCart::getDishId, dishId);
            // 查找本次添加进购物车的商品是否已经存在
            ShoppingCart dishByName = this.getOne(wrapper);
            if (ObjectUtils.isNotEmpty(dishByName)) {
                // 如果已经存在的话，把数量+1再更新到购物车
                dishByName.setNumber(dishByName.getNumber() + 1);
                this.updateById(dishByName);
                // 返回更新完毕的购物车
                return dishByName;
            }

        } else {
            wrapper.eq(ShoppingCart::getSetmealId, shoppingCart.getSetmealId());
            ShoppingCart setmealById = this.getOne(wrapper);
            if (ObjectUtils.isNotEmpty(setmealById)) {
                setmealById.setNumber(setmealById.getNumber() + 1);
                this.updateById(setmealById);
                return setmealById;
            }
        }
        // 如果不存在的话，则直接添加进购物车
        this.save(shoppingCart);
        return shoppingCart;
    }
}
